(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:PostfeeCtrl
     * @description
     * # PostfeeCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('PostfeeCtrl', PostfeeCtrl);

    PostfeeCtrl.$inject = ['$scope', 'dataService', '$location', 'helper', '$rootScope', '$timeout', 'sessionService'];

    function PostfeeCtrl($scope, dataService, $location, helper, $rootScope, $timeout, sessionService) {

        $scope.listAction = function() {
            $scope.pageSize = 5;
            $scope.getList(1);
            $scope.$on('event:up-store-id', function() {
                $scope.store_id = $rootScope.store_id
                $scope.getList(1);
            });
        }

        $scope.getList = function(pageNo) {
            var user = sessionService.get("tokenUser");

            var query = {
                page_no: pageNo ? pageNo : "1",
                page_size: $scope.pageSize,
                order_by: "fare_id:desc"
            };
            query.query = {
                "store_id": $rootScope.store_id
            };

            dataService.postfeeGet(query, function(list) {
                if (list) {
                    $scope.fare_temp = list.fare_temp;
                    $scope.total_count = list.total_count;
                }
            });
        }

        $scope.areaGetQuery = function(page_no, cb) {
            var qeurys = {
                page_no: page_no,
                page_size: 1000
            };
            dataService.areaGet(qeurys).then(function(r) {
                if (r.total_count) {
                    cb(r.areas);
                }
            });
        }

        // $scope.getCity = function() {
        //     $scope.abc = {};
        //     for (var i = 1; i <= 4; i++) {
        //         $scope.areaGetQuery(i, function(res) {
        //             $scope.citys = res;
        //             for (var a in res) {
        //                 $scope.abc[res[a].area_id] = res[a].area;
        //             }
        //         });
        //     }
        //     $scope.$watch("abc", function(nVal, oVal) {
        //         $scope.citys = $scope.abc;
        //     }, true);
        // }

        $scope.addAction = function() {
            var fare_id = $location.search().fare_id;

            // console.error("编辑--", fare_id);

            $scope.fareTemplate = {};
            //选中城市
            $scope.ccity = {
                express: {},
                ems: {},
                post: {}
            };

            if (fare_id) {
                $scope.getOne(fare_id);
            } else {
                $scope.fareTemplate = {
                    "partner_id": dataService.currentLoginedUser().partner_id, //商家ID
                    //门店ID 这个暂时先写成固定的
                    "name": "邮费模板",
                    "is_incl_postage": 1, //是否包邮 1=是 2=否
                    "valuation_model": 1, //计价方式 1=计件 2=重量 3=体积
                    "carry_modes": {
                        "express": {
                            "name": "express",
                            "son_data": []
                        },
                        "ems": {
                            "name": "ems",
                            "son_data": []
                        },
                        "post": {
                            "name": "post",
                            "son_data": []
                        }
                    }
                };
            }

            // console.log("fareTemplate---->", $scope.fareTemplate);
        }

        //
        $scope.getOne = function(fare_id) {
            var query = {
                "query": {
                    "fare_id": fare_id
                }
            };
            // console.error("单个邮费模板开始查询-", query);
            //dataService.postfeeGet(query).then(function(result) {
            dataService.postfeeGet(query, function(result) {
                // console.error("result--", result);
                if (result) {
                    var fareTemplate = $scope.fareTemplate;
                    //临时变量 用于和之后新组装的数据比较
                    $scope.fare_temp_data = result.fare_temp[0];

                    fareTemplate.fare_id = $scope.fare_temp_data.fare_id;
                    fareTemplate.partner_id = $scope.fare_temp_data.partner_id;
                    fareTemplate.store_id = $scope.fare_temp_data.store_id;
                    fareTemplate.name = $scope.fare_temp_data.name;
                    fareTemplate.is_incl_postage = $scope.fare_temp_data.is_incl_postage;
                    fareTemplate.valuation_model = $scope.fare_temp_data.valuation_model;
                    fareTemplate.remark = $scope.fare_temp_data.remark;
                    // $scope.fareTemplate.carry_modes = { "express": [], "ems": [], "post": [] };

                    fareTemplate.carry_modes = {
                        "express": {
                            "name": "express",
                            "son_data": []
                        },
                        "ems": {
                            "name": "ems",
                            "son_data": []
                        },
                        "post": {
                            "name": "post",
                            "son_data": []
                        }
                    };

                    //初始化判断是否存在默认全国选项
                    var carry_modes = $scope.fare_temp_data.carry_modes;
                    var a = [];
                    for (var j in carry_modes) {
                        var c_way = carry_modes[j].carry_way;
                        a[c_way] = 1;
                        if (carry_modes[j].region == 1) {
                            a[c_way] = 2;
                        }
                    }
                    $scope.is_quanguo = {};
                    for (var m in a) {
                        if (a[m] == 1) {
                            $scope.is_quanguo[m] = true;
                        }
                    }

                    for (var i in carry_modes) {
                        var carry_way = carry_modes[i].carry_way;
                        fareTemplate.carry_modes[carry_way].son_data.push(carry_modes[i]);
                    }

                    // console.log("fareTemplate 重新组装之后--->", fareTemplate.carry_modes.ems);
                    fareTemplate.carry_modes.express.son_data = _.sortBy(fareTemplate.carry_modes.express.son_data, 'id');
                    fareTemplate.carry_modes.ems.son_data = _.sortBy(fareTemplate.carry_modes.ems.son_data, 'id');
                    fareTemplate.carry_modes.post.son_data = _.sortBy(fareTemplate.carry_modes.post.son_data, 'id');

                    $scope.fareTemplate = fareTemplate;
                }
            });
        }

        $scope.$watch('fareTemplate', function(nVal, oVal) {
            if (nVal != oVal) {
                _.map(nVal.carry_modes, function(modes, cway) {
                    _.map(modes.son_data, function(row, index) {
                        if (row.region != 1) {
                            nVal.carry_modes[cway].son_data[index].diabledCitys = diabledCitys(cway, index);
                        }
                    })
                })
            }
            // console.log("disabledCitys---->", $scope.fareTemplate);
        }, true);

        function diabledCitys(cway, index) {
            var citys = [];
            _.map($scope.fareTemplate.carry_modes[cway].son_data, function(val, key) {
                if (key != index && val.region != 1) {
                    //citys = _.union(citys, _.keys(val.region));
                    citys = _.union(citys, val.region)
                }
            })
            return citys;
        }

        //运送方式，运费模式添加
        $scope.addExpress = function(carry_way) {
            $scope.fareTemplate.carry_modes[carry_way].son_data.push({
                "carry_way": carry_way,
                "first_piece": 1,
                "first_amount": 0,
                "second_piece": 1,
                "second_amount": 0,
                "region": "1"
            });
        }

        //点击指定地区设置运费
        $scope.addCity = function(carry_way) {
            $scope.fareTemplate.carry_modes[carry_way].son_data.push({
                "carry_way": carry_way,
                "first_piece": 1,
                "first_amount": 0,
                "second_piece": 1,
                "second_amount": 0,
                "region": []
            });
        }

        //默认全国设置运费
        $scope.addQuanGuo = function(carry_way) {
            $scope.fareTemplate.carry_modes[carry_way].son_data.push({
                "carry_way": carry_way,
                "first_piece": 1,
                "first_amount": 0,
                "second_piece": 1,
                "second_amount": 0,
                "region": "1"
            });

            $scope.is_quanguo[carry_way] = false;
        }

        //判断运费方式是否
        $scope.isChecked = function($event, flag) {
            var status = $event.currentTarget.checked;

            if (status) {
                $scope.addExpress(flag);
            } else {
                $scope.fareTemplate.carry_modes[flag].son_data = [];
            }
        }

        $scope.postfeeAdd = function() {
            //把数据重新公司一下
            var data = $scope.refreshData();

            if (!data)
                return false;

            if ($scope.fareTemplate.fare_id) {
                var add_data = {};
                var aa = [];
                if (data.carry_modes.length) {
                    for (var i in data.carry_modes) {
                        if (!data.carry_modes[i].id) {
                            aa.push(data.carry_modes[i]);
                        }
                    }
                    add_data.carry_modes = aa;
                    add_data.fare_id = $scope.fareTemplate.fare_id;

                    if (add_data.carry_modes.length) {
                        dataService.postfeeAdd(add_data).then(function(resa) {
                            if (resa.fare_id) {
                                helper.myAlert("success", "#/postfee/list");
                            } else {
                                helper.myAlert("error" + resa);
                            }
                        });
                        return false;
                    }
                }

                if (!data)
                    return;
                dataService.postfeeUpdate(data).then(function(res) {
                    if (res.fare_id) {
                        helper.myAlert("success", "#/postfee/list");
                    } else {
                        helper.myAlert("error" + res);
                    }
                });
            } else {
                if (!data)
                    return;
                dataService.postfeeAdd(data).then(function(res) {
                    if (res.fare_id) {
                        helper.myAlert("success", "#/postfee/list");
                    } else {
                        helper.myAlert(res);
                    }
                });
            }
        }


        //重新整理一下添加的数据
        $scope.refreshData = function() {
            var data = {};
            var carry_modes = [];

            if ($scope.fareTemplate.fare_id) {
                data.fare_id = $scope.fareTemplate.fare_id;
            }

            data.partner_id = $scope.fareTemplate.partner_id;
            data.store_id = $rootScope.store_id;

            data.name = $scope.fareTemplate.name;
            data.is_incl_postage = parseInt($scope.fareTemplate.is_incl_postage);
            data.valuation_model = parseInt($scope.fareTemplate.valuation_model);
            data.remark = $scope.fareTemplate.remark;
            console.error("1data",$scope.fareTemplate);
            console.error("1data",data);
            var carry = $scope.fareTemplate.carry_modes;
            for (var i in carry) {
                if (carry[i].son_data.length) {
                    var carry_data = carry[i].son_data;
                    for (var j in carry_data) {
                        if (carry_data[j].region == "1") {
                            var region = "1";
                        } else {
                            var region = carry_data[j].region.join(",");
                        }

                        if (!region) {
                            helper.myAlert("error:请选择运送地区！");
                            return false;
                        }

                        var a = {
                            "carry_way": carry_data[j].carry_way,
                            "first_amount": carry_data[j].first_amount,
                            "first_piece": carry_data[j].first_piece,
                            "region": region,
                            "second_amount": carry_data[j].second_amount,
                            "second_piece": carry_data[j].second_piece
                        }
                        if (carry_data[j].id) {
                            a.id = carry_data[j].id;
                        }
                        carry_modes.push(a);
                    }
                }
            }

            data.carry_modes = carry_modes;

            return data;
        }

        //删除
        $scope.carryModesDelete = function(fare_id, id, flag, index) {
            var data = {};

            if (fare_id) {
                data.fare_id = fare_id;
            }

            if (id) {
                data.id = id;
            } else {
                $timeout(function() {
                    $scope.fareTemplate.carry_modes[flag].son_data.splice(index, 1);
                });
                return false;
            }
            dataService.postfeeDelete(data).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $scope.getOne(data.fare_id);
                    });
                }
            });
        }

        $scope.postfeeDelete = function(fare_id) {
            var data = {};

            if (fare_id) {
                data.fare_id = fare_id;
            }

            dataService.postfeeDelete(data).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("erro:" + r.Msg);
                } else {
                    helper.myAlert("success", null, null, function() {
                        $scope.listAction();
                    });
                }
            });
        }
    }
})();